package com.javen.demo;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Javen
 * 读写锁
 */
@Slf4j
public class ReadWriteLockDemo {

    private final Map<String, String> map = new HashMap<>();
    // 可重入的读写锁
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void put(String key, String value) {
        try {
            rwLock.writeLock().lock();
            log.info("{} 正在写", Thread.currentThread().getId());
            map.put(key, value);
            log.info("{} 写入完成", Thread.currentThread().getId());
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    public void get(String key) {
        try {
            rwLock.readLock().lock();
            log.info("{} 正获取", Thread.currentThread().getId());
            String value = map.get(key);
            log.info("{} 获取完成, {} = {}", Thread.currentThread().getId(), key, value);
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public void clearMap() {
        map.clear();
    }

    public static void main(String[] args) {
         ReadWriteLockDemo cache = new ReadWriteLockDemo();

        for (int i = 0; i < 5; i++) {
            final String temp = i + "";
            new Thread(() -> cache.put(temp, temp), String.valueOf(i)).start();
        }

        for (int i = 0; i < 5; i++) {
            String temp = i + "";
            new Thread(() -> cache.get(temp), String.valueOf(i)).start();
        }
    }
}
